package per.hx.bs.web.yw.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import per.hx.bs.base.BaseController;
import per.hx.bs.base.annotation.BsCLog;
import per.hx.bs.base.domain.ExcelData;
import per.hx.bs.base.domain.ReturnDTO;
import per.hx.bs.entity.sys.SysUserDO;
import per.hx.bs.entity.yw.YwAppraisalRecordDO;
import per.hx.bs.entity.yw.YwSettlementDO;
import per.hx.bs.util.DateUtils;
import per.hx.bs.util.ExcelUtils;
import per.hx.bs.util.PageUtils;
import per.hx.bs.util.Query;
import per.hx.bs.web.sys.service.SysUserService;
import per.hx.bs.web.yw.service.YwAppraisalUserService;
import per.hx.bs.web.yw.service.YwSettlementService;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.*;

/**
 * @author HuXing
 * @date 2018/4/30  19:02
 */
@Controller
@RequestMapping(value = "yw/settlement")
public class SettlementController extends BaseController {

    private final
    YwSettlementService settlementService;

    private final
    YwAppraisalUserService appraisalUserService;
    private final
    SysUserService userService;

    private final
    String prefix = "yw/settlement";

    private static final int B = 100000;

    @Autowired
    public SettlementController(YwSettlementService settlementService, YwAppraisalUserService appraisalUserService, SysUserService userService) {
        this.settlementService = settlementService;
        this.appraisalUserService = appraisalUserService;
        this.userService = userService;
    }

    @BsCLog("进入结算页面")
    @RequiresPermissions("yw:settlement:settlement")
    @GetMapping(value = "/{userId}")
    public String settlement(@PathVariable("userId") Long userId, String date, Model model) {
        model.addAttribute("userId", userId);
        model.addAttribute("date", date);
        return prefix + "/settlement";
    }

    @BsCLog("获取结算数据")
    @RequiresPermissions("yw:settlement:settlement")
    @GetMapping(value = "/list")
    @ResponseBody
    public PageUtils settlement(Map<String, Object> params) {
        Query query = new Query(params);
        List<YwAppraisalRecordDO> recordDOS = appraisalUserService.list(query);
        int total = appraisalUserService.count(query);
        return new PageUtils(recordDOS, total);
    }

    @BsCLog("结算")
    @RequiresPermissions("yw:settlement:settlement")
    @GetMapping(value = "/user/{userId}")
    @ResponseBody
    public ReturnDTO settlement(@PathVariable("userId") Long userId, String settlement) {

        int a = settlementService.settlement(userId, settlement, getName());
        if (a == B) {
            return ReturnDTO.error("当前时间无可可结算指标");
        }
        return ReturnDTO.check(a);
    }

    @GetMapping(value = "/count")
    public String deptList() {
        return prefix + "/deptList";
    }

    @BsCLog("部门统计")
    @GetMapping(value = "/count/data")
    @ResponseBody
    public PageUtils deptData(@RequestParam Map<String, Object> map) {
        String searchDate = "searchDate";
        if (null == map.get(searchDate) || "".equals(map.get(searchDate))) {
            map.put(searchDate, DateUtils.format(new Date(), "yyyy-MM"));
        }
        List<YwSettlementDO> settlementDOS = settlementService.listAsDept(map);
        return new PageUtils(settlementDOS, settlementDOS.size());
    }

    @BsCLog("人员展示")
    @GetMapping(value = "/user")
    public String userList(Long deptId, Model model) {
        model.addAttribute("deptId", deptId);
        return prefix + "/userList";
    }

    @BsCLog("人员展示")
    @GetMapping(value = "/user/data")
    @ResponseBody
    public PageUtils userData(@RequestParam("deptId") Long deptId, @RequestParam("searchDate") String searchDate) {

        if (deptId == null) {
            return null;
        }

        if (null == searchDate || "".equals(searchDate)) {
            searchDate = DateUtils.format(new Date(), "yyyy-MM");
        }
        List<YwSettlementDO> settlementDOS = settlementService.listAsUser(deptId, searchDate);
        return new PageUtils(settlementDOS, settlementDOS.size());
    }

    @BsCLog("导出excel")
    @RequiresPermissions("yw:kh:excel")
    @GetMapping(value = "/excel/{id}")
    @ResponseBody
    public void excel(@PathVariable("id") Long id, HttpServletResponse response) {

        YwSettlementDO settlementDO = settlementService.selectOne(id);
        Long userId = settlementDO.getUserId();


        SysUserDO userDO = userService.get(userId);
        ExcelData excelData = new ExcelData();
        excelData.setSubject("绩效考核详情");
        excelData.setMessage("考核用户：" + userDO.getName() + "导出人:" + getName() + "   导出时间:" + DateUtils.formatDateTime(new Date()));
        excelData.setName(userDO.getName() + "绩效考核.xlsx");
        List<String> titles = new ArrayList<String>();
        titles.add("一级指标");
        titles.add("二级指标");
        titles.add("指标类型");
        titles.add("单项金额");
        titles.add("金额类型");
        titles.add("考核数量");
        titles.add("最终金额");
        titles.add("录入时间");
        List<String> titleTwo = new ArrayList<String>();
        titles.add("岗位名称");
        titles.add("岗位绩效");
        titles.add("考核奖励");
        titles.add("考核扣除");
        titles.add("考核所得");
        titles.add("绩效总额");
        titles.add("用户名称");
        titles.add("管理人员");
        excelData.setTitles(titles);

        Map<String, Object> map = new HashMap<String, Object>(2);
        map.put("userId", userId);
        map.put("isJsId", id);
        List<YwAppraisalRecordDO> recordDOS = appraisalUserService.list(map);

        List<List<Object>> rows = new ArrayList<List<Object>>();

        if (recordDOS != null && !recordDOS.isEmpty()) {
            for (YwAppraisalRecordDO recordDO : recordDOS) {
                List<Object> row = new ArrayList<Object>();
                row.add(recordDO.getTypeName());
                row.add(recordDO.getItemName());
                row.add("0".equals(recordDO.getItemType()) ? "奖励" : "处罚");
                row.add(recordDO.getItemMoney());
                row.add(recordDO.getItemUnit());
                row.add(recordDO.getRecordAmount());
                row.add(recordDO.getRecordMoney());
                row.add(DateUtils.formatDateTime(recordDO.getCreateDate()));
                rows.add(row);
            }
        }
        excelData.setRows(rows);
        try {
            File file = new File("C:/Users/HuXing/Desktop/" + excelData.getName());
            FileOutputStream out = new FileOutputStream(file);
            try {
                ExcelUtils.exportExcel(excelData, out);
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            ExcelUtils.exportExcel(response, excelData.getName(), excelData);
        } catch (RuntimeException r) {
            r.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
